$(function () {
    findByUserId();
});

function findByUserId() {
    let id = sessionStorage.getItem("userId");
    $.ajax({
        url: '/back/user/findById',
        data: {id: id},//js对象时key-value的形式
        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            setUserData(data.model);
        }
    })
}

function setUserData(data) {
    $("#username").val(data.username);
    $("#sex").val(data.sex);
    $("#phone").val(data.phone);
    let hobbys = data.hobby.split(",");
    $('input:checkbox[name=hobby]').each(function (index, item) {
        for (let i = 0; i < hobbys.length; i++) {
            if (item.value == hobbys[i]) {
                $(this).attr("checked", "checked");
            }
        }
    });
}

function save() {
    let data = {
        id: sessionStorage.getItem("userId"),
        username: $("#username").val(),
        phone: $("#phone").val(),
        sex: $('#sex').val(),
        hobby: getHobby().toString()
    };
    $.ajax({
        url: '/back/user/update',
        data: data,//js对象时key-value的形式
        type: 'post',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            if (data.result == "success") {
                toRight("/html/back/user/userManage.html");
            } else if (data.result == "isHave") {
                alert("当前用户名已经存在，请重写");
            } else {
                alert("很遗憾，你的修改失败");
            }
        }
    })

}

function getHobby() {
    let vals = [];
    $('input:checkbox[name=hobby]:checked').each(function (index, item) {
        vals.push($(this).val());//数组的赋值  push
    });
    return vals;
}